package com.wuliu.action.sys;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import beartool.MD5;
import com.wuliu.action.BaseAction;
import com.wuliu.business.sys.MenuObj;
import com.wuliu.business.sys.RoleObj;
import com.wuliu.business.sys.UserObj;
import com.wuliu.model.common.PageVO;
import com.wuliu.model.common.QueryVO;
import com.wuliu.model.sys.Menu;
import com.wuliu.model.sys.Role;
import com.wuliu.model.sys.User;
import com.wuliu.util.BaseUtil;
import com.wuliu.util.DbUtil;

public class UserAction extends BaseAction {
	private User user;
	
    public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String userList() {  
		List<QueryVO> list = new ArrayList<QueryVO>(); 
        QueryVO USER_ID = new QueryVO("A.USER_ID", "选择", "checkbox", "chioce", "");
        list.add(USER_ID); 
        
        QueryVO  USER_ACCOUNT = new QueryVO("A.USER_ACCOUNT", "账号", "1");
        list.add(USER_ACCOUNT);
        
        QueryVO  USER_NAME = new QueryVO("A.USER_NAME", "姓名", "1");
        list.add(USER_NAME);
        
        QueryVO USER_DESC = new QueryVO("A.USER_DESC", "描述", "1");
        list.add(USER_DESC);
        
        QueryVO USER_USER = new QueryVO("A.USER_SPOT", "所属配送点", "1");
        list.add(USER_USER);
        
        QueryVO USER_TEL = new QueryVO("A.USER_TEL", "电话", "1");
        list.add(USER_TEL);
        
        QueryVO ACTIVE_FLAG = new QueryVO("(CASE WHEN A.ACTIVE_FLAG='0' THEN '可用' ELSE '不可用' END) AS ACTIVE_FLAG ", "是否可用", "1");
        list.add(ACTIVE_FLAG);
        
        QueryVO ADD_BY = new QueryVO("A.ADD_BY", "创建人", "1");
        list.add(ADD_BY);  
        
        QueryVO ADD_DATE = new QueryVO("A.ADD_DATE", "创建日期", "1");
        list.add(ADD_DATE);
        
        QueryVO ADD_TIME = new QueryVO("A.ADD_TIME", "创建时间", "1");
        list.add(ADD_TIME);
        
        QueryVO UPD_BY = new QueryVO("A.UPD_BY", "最后修改人", "1");
        list.add(UPD_BY);  
        
        QueryVO UPD_DATE = new QueryVO("A.UPD_DATE", "最后修改日期", "1");
        list.add(UPD_DATE);
        
        QueryVO UPD_TIME = new QueryVO("A.UPD_TIME", "最后修改时间", "1");
        list.add(UPD_TIME);
        

        String intStr = "1000";// 需要特殊显示的标记;在原来基础上加1000 
        String tableName = "  WL_USER A WHERE 1=1 ";  
 	    
        String orderStr = " ORDER BY A.USER_NAME ASC "; 
       
        HashMap<String, String> hm = null; //DBHelper.formQueryToken(request);
        HashMap<String, String> hmSearch = new HashMap<String, String>();
        String searchFlag = BaseUtil.getStr(request.getParameter("searchFlag"));
        String s_user_name = BaseUtil.getStr(request.getParameter("s_user_name"));
        String s_user_desc = BaseUtil.getStr(request.getParameter("s_user_desc"));  
        
    	 if(!s_user_name.equals("")){
           	tableName += " AND A.USER_NAME LIKE '%"+s_user_name+"%' "; 
           	hmSearch.put("s_user_name", s_user_name);
         }
    	 if(!s_user_desc.equals("")){
           	tableName += " AND A.USER_DESC LIKE '%"+s_user_desc+"%'";
           	hmSearch.put("s_user_desc", s_user_desc);
         } 
    	 
        String pageNum = BaseUtil.getStr(request.getParameter("pageNums"));
        if(pageNum==null||pageNum.equals(""))
            pageNum = "1"; 
        List<?> resultL = DbUtil.queryStrForPage(list, tableName, intStr, hm, orderStr, Integer.parseInt(pageNum));
        int queryCount = DbUtil.queryStrCount(list, tableName, intStr, hm, orderStr);
        PageVO vo = DbUtil.pageObjFor(resultL, pageNum, queryCount);  
        
        request.setAttribute("hmSearch", hmSearch);
        request.setAttribute("searchFlag", searchFlag); 
         
        request.setAttribute("voResult", vo);
        request.setAttribute("qList", list);// 显示名称 
        return "userList";
	}
    
    public String saveUser(){

    	if(BaseUtil.getStr(user.getUserId()).equals("")){
        	if(BaseUtil.getStr(UserObj.getUserByAccount(user.getUserAccount()).getUserAccount()).equals("")){
        		String sql	= "INSERT INTO WL_USER(USER_ID,USER_ACCOUNT,USER_PWD,USER_NAME," +
        				"USER_DESC,USER_SPOT,USER_TEL,ACTIVE_FLAG,ADD_DATE,ADD_TIME,ADD_BY) " +
        				" VALUES(?,?,?,?,?,?,?,?,DATE_FORMAT(NOW(),'%Y%m%d') ,DATE_FORMAT(NOW(),'%H%i%s'),?)";
        		List<String> lt = new ArrayList<String>();
        		lt.add(user.getUserAccount());
        		lt.add(user.getUserAccount());
        		MD5 md5 = new MD5();
                lt.add(md5.getMD5ofStr("00000000"));
        		lt.add(user.getUserName());
        		lt.add(user.getUserDesc());
        		lt.add(user.getUserSpot());
        		lt.add(user.getUserTel());
        		lt.add(user.getActiveFlag());
        		lt.add(((User)session.get("user")).getUserName());
        		boolean result	= DbUtil.excuSQL(lt, sql);
        		if(result){
        			request.setAttribute("showMsg","新增成功！");
        		}else{
        			request.setAttribute("showMsg","新增失败！");
        		} 		
        	}else{
        		request.setAttribute("showMsg","该编号已存在！");
        	}
    	}else{
    		String sql	= "UPDATE WL_USER SET USER_NAME=?,USER_DESC=?,USER_SPOT=?," +
    				"USER_TEL=?,ACTIVE_FLAG=?,UPD_DATE=DATE_FORMAT(NOW(),'%Y%m%d')," +
    				"UPD_TIME=DATE_FORMAT(NOW(),'%H%i%s'),UPD_BY=? WHERE USER_ID=? ";
    		List<String> lt = new ArrayList<String>();
    		
    		lt.add(user.getUserName());
    		lt.add(user.getUserDesc());
    		lt.add(user.getUserSpot());
    		lt.add(user.getUserTel());
    		lt.add(user.getActiveFlag());
    		lt.add(((User)session.get("user")).getUserName());
    		lt.add(user.getUserId());
    		boolean result	= DbUtil.excuSQL(lt, sql);
    		if(result){
    			request.setAttribute("showMsg","更新成功！");
    		}else{
    			request.setAttribute("showMsg","更新失败！");
    		} 		
    	}
    	return userList();
    }
    
    public String getUserInfo(){
    	String id	= BaseUtil.getStr(request.getParameter("id"));
    	User user = UserObj.getUserById(id);

    	JSONObject json = JSONObject.fromObject(user);
    	try {
			response.setCharacterEncoding("utf8");
			response.getWriter().print(json.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return null;
    }
    
	 public String delUser(){
		 String id	= request.getParameter("id");

		 String sql	= "DELETE FROM WL_USER WHERE USER_ID ='"+id+"'";

		 boolean result	= DbUtil.execute(sql);
		 if(result){
			 request.setAttribute("showMsg","删除成功！");
		 }else{
			 request.setAttribute("showMsg", "删除失败！");
		 }
		 return userList();
	 }
	 
	 public String getUserRole(){
    	String id	= BaseUtil.getStr(request.getParameter("id"));
    	User user = UserObj.getUserById(id);
		List<Role> roleList = RoleObj.getRoleList();
		List<Role> userRoleList = RoleObj.getRoleListByUser(user.getUserAccount());
		for(int i=0;i<roleList.size();i++){
			Role role = roleList.get(i);
			if(userRoleList!=null&&userRoleList.size()>0){
				for(int j=0;j<userRoleList.size();j++){
					Role userRole = userRoleList.get(j);
					if(role.getRoleId().equals(userRole.getRoleId())){
						role.setIsSelect("1");
					}
				}
			}
		}
		
		List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
        Map<String,Object> map = null;
        Role role = null;
        for(int i = 0;i < roleList.size();i++){
            role = roleList.get(i);
            map = new HashMap<String,Object>();
            map.put("id", BaseUtil.getStr(role.getRoleId()));
            map.put("pId", BaseUtil.getStr("0"));
            map.put("name", BaseUtil.getStr(role.getRoleName()));
            
            if(role.getIsSelect() != null && role.getIsSelect().equals("1")){
                map.put("checked",true);
                map.put("open", true);
            }
            
            result.add(map);
        }

    	JSONArray json = JSONArray.fromObject(result);
    	try {
			response.setCharacterEncoding("utf8");
			response.getWriter().print(json.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return null;
    }
	 
	public String saveUserRole(){

		String msg="";
		String userId = request.getParameter("userId");
		String roleIds = request.getParameter("roleIds");
		User user = UserObj.getUserById(userId);
		JSONObject json = new JSONObject();
		//先删除绑定的角色
		String sql = "DELETE FROM WL_USER_ROLE WHERE USER_ACCOUNT='"+user.getUserAccount()+"' ";
		if(DbUtil.excu(sql)){
			sql = "INSERT INTO WL_USER_ROLE(UR_ID,USER_ACCOUNT,ROLE_ID) " +
					"VALUES(?,?,?) ";
			List<Object[]> par = new ArrayList<Object[]>();
			String[] roleIdArray = roleIds.split(",");
			for(String roleId:roleIdArray){
				Object[] ele = new Object[3];
				ele[0]=UUID.randomUUID().toString();
				ele[1]=user.getUserAccount();
				ele[2]=roleId;
				par.add(ele);
			}
			if(DbUtil.execute(sql, par)){
				msg="授权成功！";
			}else{
				msg="授权失败！";
			}
		}else{
			msg="授权失败！";
		}
		json.put("msg", msg);
        try {
        	response.setCharacterEncoding("utf8");
            response.getWriter().print(json.toString());
        } catch(Exception ee) {
            System.out.println(ee);
        }
        return null;
	}
}
